<template>
  <div class="chat-container" v-if="isVisible">
    <div class="chat-header">
      <!-- 左侧区域：图标和标题 -->
      <div class="header-left">
        <img src="../../../src/assets/image/ai.svg" alt="AI Chat" style="width: 30px; height: 30px; margin-right: 10px"/>
        <h3 class="chat-title" style="margin: 0; font-size: 1.2rem; font-weight: 500; color: #333">AI 助手</h3>
      </div>

      <!-- 右侧区域：收起按钮 -->
      <div class="header-right">
        <span style="color: #009c50" @click="clearChat()">清空</span>
        <span style="color: #009c50">|</span>
        <span style="color: #009c50" @click="$emit('toggleVisibility')">收起</span>
      </div>
    </div>

    <!-- 分隔线 -->
    <hr class="separator" />
    <div class="chat-messages" ref="messagesContainer">
      <div
        v-for="(message, index) in messages"
        :key="index"
        class="message"
        :class="message.sender"
      >
        <div class="bubble">{{ message.text }}</div>
      </div>
    </div>

    <div class="input-area">
      <input
        v-model="userInput"
        @keyup.enter="sendMessage"
        placeholder="輸入消息..."
        class="message-input"
      />
      <button @click="sendMessage" class="send-button">發送</button>
    </div>
  </div>
</template>
<script setup lang="ts">
const env = import.meta.env;
const serverurl: string = env["VITE_APP_BASE_API"];
import { ref, reactive,onBeforeUnmount } from "vue";
const messages = ref([]); // 使用ref创建响应式数组
const replyMessages = reactive([]);
var userInput = ref("");
var messagesContainer = ref(null);
const eventSource = ref(null);
const props = defineProps({
  isVisible: {
    type: Boolean
  }
})

const emit = defineEmits(['toggleVisibility']);
// 组件卸载前关闭 EventSource 连接
onBeforeUnmount(() => {
  if (eventSource.value) {
    eventSource.value.close();
  }
});
const clearChat = () => {
  // 关闭当前连接
  eventSource.value?.close();
  eventSource.value = null;
  // 清空消息列表
  messages.value = [];
  // 清空输入框
  userInput.value = '';
};


const sendMessage = () => {
  // 获取用户输入并去除首尾空格
  let content = userInput.value.trim();
  // 如果用户输入为空，则直接返回
  if (!content) return;
  // 清空用户输入框
  userInput.value = "";

  // 检查输入是否包含英文字母
  const englishRegex = /[a-zA-Z]/;
  const instruction = englishRegex.test(content) ? "(请用全英文进行回答)" : "(请用全繁体进行回答)";
  const fullContent = content + instruction;
  // 只有当eventSource不存在时才创建新的EventSource连接
  if (!eventSource.value) {
    // 向消息列表中添加用户消息
    messages.value.push({
      text: content,
      sender: "user",
    });
    // 向消息列表中添加一个空的 AI 消息占位符
    messages.value.push({ text: "", sender: "ai" });
     // 创建新的 EventSource 连接
     createEventSource(fullContent);
  }
};

// 创建 EventSource 连接的函数
const createEventSource = (content) => {
    eventSource.value = new EventSource(serverurl + "/chat?content=" + content);
    // 设置消息接收的回调函数
    eventSource.value.onmessage = (event) => handleMessage(event);
    // 监听错误事件，以便在出现问题时能够重新连接或处理错误
    eventSource.value.onerror = (error) => handleError(error);
};


// 处理接收到的消息的函数
const handleMessage = (event) => {
  if(event.type === 'message') {
    try {
        const data = JSON.parse(event.data);
        messages.value[messages.value.length - 1].text += data.result;
    } catch (parseError) {
        console.error("Failed to parse JSON data:", parseError);
    }
}else if(event.type === 'error') {
    handleError(event);
}
};

// 处理 EventSource 错误的函数
const handleError = (error) => {
    console.error("EventSource failed:", error);
    // 关闭出错的连接
    eventSource.value.close();
    // 重置 eventSource 变量，允许重建连接
    eventSource.value = null;
};
</script>

  <style scoped>
.chat-container {
  border: 1px solid #007bff;
  position: fixed;
  bottom: 80px;
  right: 20px;
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
  height: 80vh;
  display: flex;
  flex-direction: column;
  /* border: 1px solid #e0e0e0; */
  border-radius: 8px;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f5f5f5;
}

.message {
  margin: 10px 0;
  display: flex;
}

.message.user {
  justify-content: flex-end;
}

.message.ai {
  justify-content: flex-start;
}

.bubble {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 15px;
  word-break: break-word;
}

.user .bubble {
  background-color: #007bff;
  color: white;
}

.ai .bubble {
  background-color: #ffffff;
  border: 1px solid #e0e0e0;
}

.input-area {
  display: flex;
  padding: 15px;
  background-color: white;
  border-top: 1px solid #e0e0e0;
}

.message-input {
  flex: 1;
  padding: 10px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  margin-right: 10px;
}

.send-button {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.send-button:hover {
  background-color: #0056b3;
}

.header-left,
.header-right {
  display: flex;
  align-items: center;
}
.chat-header {
  display: flex;
  align-items: center;
  padding: 10px 24px;
  background-color: #f8f9fa;
  justify-content: space-between;
}

.chat-header img {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

/* 分隔线样式 */
.separator {
  height: 1px;
  background-color: #e0e0e0;
  border: none;
  margin: 0;
}
/* 或者根据深色模式动态调整 */
@media (prefers-color-scheme: dark) {
  .ai .bubble {
    color: #000000 !important; /* 黑色 */
    background-color: #ffffff;
    border: 1px solid #e0e0e0;
  }
}
</style>
